package gggameserver.testbed;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import net.schmizz.sshj.connection.ConnectionException;
import net.schmizz.sshj.connection.channel.direct.Session.Command;

public class GGCommandResult {

	Integer exitCode;
	StringBuilder log = new StringBuilder();

	private BufferedReader in;
	private PrintWriter out;
	private BufferedReader inStdErr;
	private Thread stderrThread;
	
	public GGCommandResult(Command command) {
		this.in = new BufferedReader(new InputStreamReader(command.getInputStream()));
		this.inStdErr = new BufferedReader(
				new InputStreamReader(command.getErrorStream()));
		this.out = new PrintWriter(command.getOutputStream(), false);

		X xout = new X(this.in, "OUT");
		X xerr = new X(this.inStdErr, "ERR");
		
		try {
			command.join();
		} catch (ConnectionException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		try {
			xout.join();
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		try {
			xerr.join();
		} catch (InterruptedException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
		try {
			this.in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			this.inStdErr.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		this.out.close();
		
		this.exitCode = command.getExitStatus();
	}
	
	private synchronized void addOutputLine(X x, String line) {
		log.append(x.name);
		log.append('>');
		log.append(line);
		log.append('\n');
	}
	
	class X extends Thread {
		public String name;
		BufferedReader reader;
		public X(BufferedReader reader, String name) {
			this.name = name;
			this.reader = reader;
			this.setDaemon(true);
			this.start();
		}
		@Override
		public void run() {
			try {
				String line;
				while ((line = reader.readLine()) != null)
					addOutputLine(this, line);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public synchronized String getLog() {
		return log.toString();
	}

	public Integer getExitCode() {
		return exitCode;
	}
	
}
